package 面试v1.字节;

public class LeetCode19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //虚拟节点避免头指针判断
        ListNode virtual = new ListNode(0, head);
        if (n <= 0) {
            return head;
        }
        ListNode preIndex = virtual, secondIndex = head, pre = head;
        while (n != 0 && secondIndex != null) {
            secondIndex = secondIndex.next;
            n--;
        }

        if (n > 0) {
            return head;
        }

        while (secondIndex != null) {
            preIndex = preIndex.next;
            secondIndex = secondIndex.next;
        }
        preIndex.next = preIndex.next.next;
        return virtual.next;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
